﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace OpenQuarters.EntityBase
{
    public static class Utils
    {
        public static List<Type> GetSubclassesOf(Type type, bool ignoreSystem)
        {
            List<Type> lReturn = new List<Type>();
            foreach (var a in System.Threading.Thread.GetDomain().GetAssemblies())
            {
                if (ignoreSystem && a.FullName.StartsWith("System."))
                {
                    continue;
                }
                foreach (var t in a.GetTypes() )
                {
                    if (t.IsSubclassOf(type) || (type.IsInterface && t.GetInterfaces().FirstOrDefault(e => e.FullName == type.FullName) != null))
                    {
                        lReturn.Add(t);
                    }
                }
            }
            return lReturn;
        }

        public class ContextItem
        {
            public static T GetItem<T>(string key, Func<T> defaultValue)
            {
                if (HttpContext.Current != null)
                {
                    if (HttpContext.Current.Items[key] == null)
                    {
                        HttpContext.Current.Items[key] = defaultValue();
                    }
                    return (T)HttpContext.Current.Items[key];
                }
                return defaultValue();
            }

            public static void SetItem<T>(string key, T value)
            {
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Items[key] = value;
                }
            }
        }
    }
}
